<template>
  <view v-if="visible" class="toast-container">
    <view class="toast-content" :class="typeClass">
      <IconFont v-if="icon" :name="iconName" class="toast-icon" />
      <text class="toast-text">{{ message }}</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'

/**
 * Toast组件
 * @description 自定义Toast提示组件，替代wx.showToast
 */

// Props
interface Props {
  message: string
  type?: 'success' | 'error' | 'loading' | 'none'
  duration?: number
  visible: boolean
}

const props = withDefaults(defineProps<Props>(), {
  type: 'none',
  duration: 1500
})

// Emits
const emit = defineEmits<{
  close: []
}>()

// 状态
const visible = ref(props.visible)

// 计算属性
const typeClass = computed(() => {
  return {
    'toast-success': props.type === 'success',
    'toast-error': props.type === 'error',
    'toast-loading': props.type === 'loading',
    'toast-none': props.type === 'none'
  }
})

const iconName = computed(() => {
  switch (props.type) {
    case 'success':
      return 'check'
    case 'error':
      return 'close'
    case 'loading':
      return 'loading'
    default:
      return ''
  }
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  visible.value = newVal
  
  if (newVal && props.duration > 0) {
    setTimeout(() => {
      visible.value = false
      emit('close')
    }, props.duration)
  }
})

// 监听props变化
watch(() => props.message, (newVal) => {
  if (newVal) {
    visible.value = true
  }
})
</script>

<style scoped>
.toast-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  pointer-events: none;
}

.toast-content {
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 200rpx;
  max-width: 400rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.3);
  animation: toastFadeIn 0.3s ease-out;
}

.toast-icon {
  margin-right: 12rpx;
  font-size: 32rpx;
}

.toast-text {
  font-size: 28rpx;
  line-height: 1.4;
  text-align: center;
}

.toast-success {
  background: rgba(76, 175, 80, 0.9);
}

.toast-error {
  background: rgba(244, 67, 54, 0.9);
}

.toast-loading {
  background: rgba(33, 150, 243, 0.9);
}

.toast-loading .toast-icon {
  animation: spin 1s linear infinite;
}

@keyframes toastFadeIn {
  from {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 